package cn.mumzone.pos.presenter;

import android.text.TextUtils;

import java.util.List;
import java.util.Observable;

import cn.mumzone.basic.BaseApplication;
import cn.mumzone.basic.mvp.AbsPresenter;
import cn.mumzone.basic.net.http.callback.ApiCallBack;
import cn.mumzone.basic.net.response.BaseResponse;
import cn.mumzone.basic.util.DeviceIdUtils;
import cn.mumzone.basic.util.ListUtil;
import cn.mumzone.basic.util.PatternUtils;
import cn.mumzone.basic.util.StringUtils;
import cn.mumzone.pos.AppConstants;
import cn.mumzone.pos.MyApplication;
import cn.mumzone.pos.api.ApiRequest;
import cn.mumzone.pos.model.IntegralRoleEntity;
import cn.mumzone.pos.model.LevelListEntity;
import cn.mumzone.pos.model.LoginEntity;
import cn.mumzone.pos.model.source.AppRepository;
import cn.mumzone.pos.model.source.MemberRepository;
import cn.mumzone.pos.model.source.UserRepository;
import cn.mumzone.pos.presenter.contract.LoginContract;

/**
 * Created by lijiateng on 2018/12/10.
 */

public class LoginPresenter extends AbsPresenter<LoginContract.View, UserRepository> implements LoginContract.Presenter {

    private int count = 0;

    private AppRepository mAppRepo;
    private MemberRepository mMemberRepo;

    private boolean memberLevelReturn = false;
    private boolean integralRoleReturn = false;

    private LoginEntity loginUser;

    private String deviceId = DeviceIdUtils.getDeviceId();

    @Override
    protected void initOtherRepository() {
        mAppRepo = new AppRepository();
        mMemberRepo = new MemberRepository();
    }

    @Override
    public void getUserInfo(String phone, String pwd) {

        if (!checkInput(phone, pwd)) {
            return;
        }

        ApiCallBack<LoginEntity> callBack = new ApiCallBack<LoginEntity>() {
            @Override
            public void onSuccess(LoginEntity loginEntity) {
                if (loginEntity != null) {
                    loginUser = loginEntity;
                    getMemberLevel(loginEntity.getShopId());
                    AppConstants.TEMP_SHOP_ID = loginEntity.getShopId();
                    getAllIntegralRuleInfo();


//                    JPushInterface.setDebugMode(BuildConfig.DEBUG);    // 设置开启日志,发布时请关闭日志
//                    JPushInterface.init(MyApplication.getInstance());
//                    JPushInterface.setAlias(MyApplication.getInstance(), 0, AppConstants.TEMP_SHOP_ID);//设置设备别名
                }
            }

            @Override
            public void onError(BaseResponse response) {
                mView.showError(response.getMsg());
            }
        };

        mRepo.getUserInfo(phone, pwd, deviceId, callBack);
        addSubscrebe(callBack);

    }

    /**
     * 获取会员等级信息
     */
    private void getMemberLevel(String orgId) {
        ApiCallBack<List<LevelListEntity>> levelCallback = new ApiCallBack<List<LevelListEntity>>() {

            @Override
            public void onSuccess(List<LevelListEntity> levelList) {
                memberLevelReturn = true;
                mMemberRepo.saveMemberLevel(levelList);
                mView.onUserLogin();

            }

            @Override
            public void onError(BaseResponse response) {
                memberLevelReturn = true;
                mView.showError(response.getMsg());
                mView.onUserLogin();
            }
        };

        mMemberRepo.getMemberLevel(orgId, levelCallback);
        addSubscrebe(levelCallback);

    }


    private void getAllIntegralRuleInfo() {
        ApiCallBack<IntegralRoleEntity> callBack = new ApiCallBack<IntegralRoleEntity>() {

            @Override
            public void onSuccess(IntegralRoleEntity roleEntity) {
                integralRoleReturn = true;
                if (roleEntity != null) {
                    mRepo.saveIntegralRole(roleEntity);
                }
                mView.onUserLogin();

            }

            @Override
            public void onError(BaseResponse response) {
                integralRoleReturn = true;
                mView.showError(response.getMsg());
                mView.onUserLogin();
            }
        };

        mRepo.getAllIntegralRuleInfo(callBack);
        addSubscrebe(callBack);

    }

    /**
     * 检查输入内容
     *
     * @param phone
     * @param pwd
     * @return
     */
    public boolean checkInput(String phone, String pwd) {

        // 校验手机号
        if (!PatternUtils.isMobileNO(phone)) {
            mView.showError("请输入正确的手机号");
            return false;
        }

        //校检登录密码格式
        if (!PatternUtils.checkPassWord(pwd)) {
            mView.showError("密码格式不正确");
            return false;
        }

        //校检登录密码6-20
        if (!PatternUtils.checkPassWordLength(pwd)) {
            mView.showError("请输入6-20位的登录密码");
            return false;
        }

        return true;
    }

    public void changeAddress(String address, String posCode) {
        // 规范格式
        if (!TextUtils.isEmpty(address)) {
            String addressUrl = address.replaceAll(" ", "").replaceAll("。", ".");
            String baseUrl = "http://" + addressUrl + "/";
            ApiRequest.init(baseUrl);
            mAppRepo.saveBaseUrl(baseUrl);
        }

        // 更新用户输入的 deviceId
        if (isDebugMode() && !TextUtils.isEmpty(posCode)) {
            deviceId = posCode;
        }
    }

    public void onClickCount() {
        if (count < 10) {
            count++;
        } else {
            mView.onDebugModeOpened();
        }
    }

    private boolean isDebugMode() {
        return count >= 10;
    }

    public void onClickAddress() {
        if (isDebugMode()) {
            mView.showChangeAddressDialog();
        }
    }

    public boolean isAllDataReady() {
        if (memberLevelReturn && integralRoleReturn) {
            mRepo.saveUserInfo(loginUser);
            return true;
        }
        return false;
    }
}
